-- UIWorkshopStrengthen
-- Create by zouyb
-- 炼金熔炉强化界面

require "game/ui/form/workshop/UIWorkshopDesc"
require "game/ui/form/workshop/UIStrengthenDetail"

local MAX_TAB_NUM = 3;

--UIWorkshopStrengthen继承自Layer
UIWorkshopStrengthen = class("UIWorkshopStrengthen", function()
    return cc.Layer:create();
end);

function UIWorkshopStrengthen.create()
    return UIWorkshopStrengthen.new();
end

local resize;

-- 最大行数
local MAX_GRID_ROW    = 2;
local PAGE_COLUMN     = 3;

local tabNames;

--构造函数
function UIWorkshopStrengthen:ctor()
    self:setName("UIWorkshopStrengthen");

    tabNames = {getLocStr("tab_title_strengthen"), getLocStr("tab_title_res"), getLocStr("tab_title_summon")};

    --初始化
    local node = cc.CSLoader:createNode("layout/workshop/WorkshopStrengthen.csb");
    self:addChild(node);
    self.node = node;

    local templateNode = findChildByName(self.node, "CT/template");

    local scrollview = findChildByName(self.node, "CT/template/scroll_view");
    self.scrollView = scrollview;
    self.initHeight = scrollview:getInnerContainerSize().height;
    self.scrollView:setVisible(true);

    -- 角标重置为炼金仓库的
    local leftBg = findChildByName(self.node, "CT/template/bg_type");
    local rightBg = findChildByName(self.node, "CT/template/bg_type2");
    leftBg:loadTexture(getTitleBgIconPath("alchemy"));
    rightBg:loadTexture(getTitleBgIconPath("alchemy"));

    -- 上下滑动，需要显示上下蒙版
    local mask1 = findChildByName(self.node, "CT/template/mask1");
    mask1:setVisible(true);

    local mask2 = findChildByName(self.node, "CT/template/mask2");
    mask2:setVisible(true);

    resize(self);

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 初始化标签
    self:initTabs();
    self:selectTab(1);

    -- 初始化格子
    self:initGrids();

    -- 重绘
    self:redraw();

end

-- 注册事件处理回调函数
function UIWorkshopStrengthen:registerEventCallback()
    -- 工坊信息更新回调
    EventMgr.register("UIWorkshopStrengthen", event.WS_STRENGTHEN_INFO, function()
        self:selectTab(self.selectIndex);

        self:initGrids();
        self:redraw();
    end);

    -- 注册获得焦点的回调
    EventMgr.register("UIWorkshopStrengthen", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UIWorkshopStrengthen" then
            if AlchemyWorkshopM.isAllGuideFinished() then
                UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_MONEY, TOPMENU_FRAME_GEM);
            end
        end
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            EventMgr.removeAll("UIWorkshopStrengthen");

            local uiForm = UIMgr.getCurrentScene():getFormByName("UINewWorkshop");
            if uiForm then
                uiForm:showBottomMenu();
            end
        elseif ev == "enter" then

            local uiForm = UIMgr.getCurrentScene():getFormByName("UINewWorkshop");
            if uiForm then
                uiForm:hideBottomMenu();
            end
        end
    end);
end

-- 注册点击事件
function UIWorkshopStrengthen:registerTouchEvent()
    -- 设置标题样式
    local titleLabel = findChildByName(self.node, "CT/template/title");
    titleLabel:setString(getLocStr("workshop_strengthen"));
    TextStyleM.setTitleStyle(titleLabel);

    -- 副标题
    local subHeadLabel = findChildByName(self.node, "CT/template/subhead");
    TextStyleM.setSubheadStyle(subHeadLabel);
    self.subHeadLabel = subHeadLabel;

    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 是否需要播放创建试剂工厂的动画
            local uiForm = UIMgr.getCurrentScene():getFormByName("UINewWorkshop");
            if self.playBuildReagentEffect then
                uiForm:playBuildReagentEffect();
            end

            if self.playBuildArtifactEffect then
                uiForm:playBuildArtifactRoomEffect();
            end

            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIWorkshopStrengthen");
        end
    end
    AddTouchEventListener(btnBack, onBackClick);
    AddBackEventHandler(self, btnBack, btnBack.touchEventListener);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 注册说明点击事件
    local btnDesc= findChildByName(self.node, "BT/desc");
    local function onDescClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            local uiDesc = UIWorkshopDesc.create();
            UIMgr:getCurrentScene():addForm(uiDesc);
        end
    end
    btnDesc:addTouchEventListener(onDescClick);
    TextStyleM.setTextStyle(btnDesc, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnDesc:setTitleText(getLocStr("btn_text_help"));
end

-- 初始化页签
function UIWorkshopStrengthen:initTabs()
    self.tabList = {};

    local startX = 0;
    local gap = 97;

    for i = 1, MAX_TAB_NUM do
        local tab = findChildByName(self.node, "CT/tabs/tab"..i);
        local icon = findChildByName(tab, "icon");
        icon:setTag(i);
        tab:setTag(i);

        -- 初始化标签名
        local text = findChildByName(tab, "text");
        local tabStr = tabNames[i];
        local kerning = 0;
        if getLang() == "en" then
            kerning = -4;
        elseif getLang() == "fr" then
            kerning = -2;
        end
        TextStyleM.setOutlineStyle(text, TextStyleM.TEXT_OUTLINE_SIZE, TextStyleM.TEXT_OUTLINE_COLOR_DARK);
        TextStyleM.setTextStyle(text, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, kerning, nil, nil, nil, nil, true, TextStyleM.getTextScale(tabStr, 6));
        text:setString(tabStr);

        if startX == 0 and i == 1 then
            startX = tab:getPositionX();
        end

        local finalList = self:getItemListByPageNo(i);
        if #finalList > 0 then
            table.insert(self.tabList, tab);
            tab:setVisible(true);
        else
            tab:setVisible(false);
        end

        icon:addTouchEventListener(function (sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                AudioM.playFx("button_click");
                -- 选中页签处理
                self:selectTab(sender:getTag());

                self:initGrids();
                self:redraw();
            end
        end);
    end

    for i = 1, #self.tabList do
        local tab = self.tabList[i];
        tab:setPositionX(startX + (i - 1) * gap);
        tab:setPositionY(tab:getPositionY() + 100);
    end

    -- tab的动画效果
    performWithDelay(self, function() self:playTabEffect(); end, 0.2);
end

-- 页签动画效果
function UIWorkshopStrengthen:playTabEffect()
    -- 带窗口动画播放结束后，页签从上面往下掉
    for i = 1, #self.tabList do
        local tab = self.tabList[i];
        local delay = 0.2 * (i - 1);
        self:dropEffect(tab, delay);
        if tab.bubbleParent and tab.bubbleParent.isVisible then
            tab.bubbleParent:setVisible(false);
            tab.bubbleParent:setOpacity(0);
            local function delayShow()
                local fadeIn = cc.FadeIn:create(0.4);
                tab.bubbleParent:setVisible(true);
                tab.bubbleParent:runAction(fadeIn);
            end
            performWithDelay(self, delayShow, delay + 0.4);
        end
    end
end

-- 掉落动画
function UIWorkshopStrengthen:dropEffect(node, delay)
    local pos = cc.p(node:getPosition());
    local delay = cc.DelayTime:create(delay);
    local moveDown = cc.MoveTo:create(0.2, cc.p(pos.x, pos.y - 100 - 5));
    local moveBack = cc.MoveTo:create(0.2, cc.p(pos.x, pos.y - 100));
    local action = cc.Sequence:create(delay, moveDown, moveBack);
    node:runAction(action);
end

-- 页签内有可强化的项
function UIWorkshopStrengthen:hasBubbles(pageNo)
    local finalList = self:getItemListByPageNo(pageNo);
    for _, info in pairs(finalList) do
        local ret = AlchemyWorkshopM.needShowBubble(info.id, info.level);
        if ret == true then
            return true;
        end
    end

    return false;
end

-- 改变页签状态
function UIWorkshopStrengthen:selectTab(index)
    self.selectIndex = index;

    local blendColor = TextStyleM.TEXT_COLOR_BLEND;
    local normalColor = TextStyleM.TEXT_COLOR_NORMAL;
    for i = 1, #self.tabList do
        local tab = self.tabList[i];
        local light = tab:getChildByName("light");
        local text = findChildByName(tab, "text");
        local bubbleParent = findChildByName(self.node, "CT/bubble_parent"..i);
        bubbleParent:setVisible(false);
        local bubble = findChildByName(bubbleParent, "bubble");
        bubbleParent:setCascadeColorEnabled(false);
        bubble:setVisible(false);

        if tab:getTag() ~= index then
            checkBlueBubbleStatus(bubble, self:hasBubbles(tab:getTag()));
            -- 先隐藏
            bubbleParent:setVisible(false);
            bubbleParent.isVisible = bubble:isVisible();
        end
        tab.bubbleParent = bubbleParent;

        if index == tab:getTag() then
            tab:setColor(normalColor);
            light:setVisible(true);
            text:setTextColor(TextStyleM.TEXT_COLOR_BROWN_YELLOW);
        else
            tab:setColor(blendColor);
            light:setVisible(false);
            text:setTextColor(TextStyleM.TEXT_COLOR_BROWN_YELLOW);
        end
    end

    self.subHeadLabel:setString(tabNames[self.selectIndex]);

    EventMgr.fire(event.WORKSHOP_ITEM_REMINDED);
end

-- 初始化单个项
function UIWorkshopStrengthen:initItem(node, info)
    local id = info.id;
    local level = info.level;

    local maxTimes = AlchemyWorkshopM.query(id, "max_strengthen_times");
    local times = info.times or 0;

    -- 如果配置了公式，那么调用公式计算最大次数
    local prefix = "formula_";
    if type(maxTimes) == "string" and
        string.startWith(maxTimes, "formula_") then
        local formulaName = string.sub(maxTimes, string.len(prefix) + 1);
        maxTimes = FormulaM.invoke(formulaName, true);
    end

    -- 图标
    local icon = findChildByName(node, "icon");
    local fileName = AlchemyWorkshopM.query(id, "icon")


    if AlchemyWorkshopM.query(id, "path") == "pet" then
        icon:loadTexture(getHeroIconPath(fileName));
    else
        icon:loadTexture(getWorkshopStrengthenIconPath(fileName));
    end

    local scale = AlchemyWorkshopM.query(id, "scale");
    if type(scale) == "number" and scale > 0 then
        icon:setScale(scale / 100);
    end

    local frame = findChildByName(node, "frame");
    fileName = AlchemyWorkshopM.query(id, "bg");
    frame:loadTexture(getWorkshopStrengthenIconPath("bg"..fileName));

    -- 是否可强化
    local canStrengthen = AlchemyWorkshopM.canStrengthen(id);

    -- 名称等级
    local levelLabel = findChildByName(node, "level");
    local color;

    if canStrengthen ~= true then
        color = TextStyleM.TEXT_COLOR_LIGHT_BLUE;
    else
        color = TextStyleM.TEXT_COLOR_BRIGHT_YELLOW;
    end
    TextStyleM.setTextStyle(levelLabel, 28, color, true, nil, nil, nil, nil, nil, true);
    TextStyleM.setShadowStyle(levelLabel, cc.size(0, -2.5));

    if times >= maxTimes then
        levelLabel:setString(getLocStr("level_max"));

    else
        levelLabel:setString(getLevelStr(level));
    end

    levelLabel:getVirtualRenderer():setAdditionalKerning(getLocKerning() -3);
    levelLabel:setPositionY(levelLabel:getPositionY() - 3);

    -- 等级为0时，背景框透明，lv.x 不显示
    if level == 0 then
        frame:setOpacity(96);
        icon:setOpacity(128);
        levelLabel:setVisible(false);
    end

    -- 泡泡节点
    local hintNode = findChildByName(node, "hint");

    -- 点击处理
    local frame = findChildByName(node, "frame");
    frame:addTouchEventListener(function (sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            local uiForm = UIStrengthenDetail.create(info);
            UIMgr.getCurrentScene():addForm(uiForm);
            AudioM.playFx("ui_open1");
        end
    end);

    -- 可以强化的话，显示右上角的气泡(只提醒一次，玩家查看后则不再提醒，重新登陆会再次提醒)
    local showBubble = AlchemyWorkshopM.needShowBubble(id, level);
    checkBlueBubbleStatus(hintNode, showBubble);
    if showBubble then
        -- 只显示一次，打开页签后自动将标记置为已提醒
        AlchemyWorkshopM.setStrengthenItemReminded(id, level);
    end

    -- 当前强化ID
    if self.curStrengthenId ~= nil and self.curStrengthenId == id then
        playEffect(frame, 1180, 75, 85);

        local levelLabel = findChildByName(node, "level");
        commonTextEffect(levelLabel);

        -- 标记正在播放强化光效的项
        self.playingStrengthenId = id;
        local function doneWithPlaying()
            self.playingStrengthenId = nil;
        end
        performWithDelay(self, doneWithPlaying, 1);

        -- 强化试剂工厂
        if self.curStrengthenId == 18 then
            -- 标记下，离开当前界面后，需要播放创建特效
            self.playBuildReagentEffect = true;
        elseif self.curStrengthenId == 16 then
            self.playBuildArtifactEffect = true;
        end

        self.curStrengthenId = 0;
    end
end

local function sortItem(item1, item2)
    local index1 = AlchemyWorkshopM.query(item1.id, "index");
    local index2 = AlchemyWorkshopM.query(item2.id, "index");
    return index1 < index2;
end

-- 获取本页签的物品项数目
function UIWorkshopStrengthen:getItemListByPageNo(pageNo)
    local list = table.values(AlchemyWorkshopM.getStrengthenList());
    local finalList = {};
    for _, info in pairs(list) do
        if AlchemyWorkshopM.query(info.id, "page") == pageNo then
            table.insert(finalList, info);
        end
    end
    return finalList;
end

-- 初始化格子
function UIWorkshopStrengthen:initGrids()
    local pageNo = self.selectIndex;

    -- 如果有正在播放的光效，保存下来
    if self.playingStrengthenId ~= nil then
        self.curStrengthenId = self.playingStrengthenId;
    end

    -- 获取列表
    local finalList = self:getItemListByPageNo(pageNo);
    if #finalList == 0 then
        return;
    end

    table.sort(finalList, sortItem);

    -- 图标间距(横向)
    local wGap = 10;

    -- 图标间距(纵向)
    local hGap = 25;

    -- 图标宽度
    local iconWidth = 140;

    -- 图片高度
    local iconHeight = 150;

    local topHGap  = 25;
    local bottomHGap  = 50;
    local leftWGap = 10;

    -- 总数
    local totalCount = #finalList;

    self.scrollView.rows = {};
    self.scrollView:removeAllChildren();

    local itemNode = cc.CSLoader:createNode("layout/workshop/StrengthenItem.csb");
    local hintNode = itemNode:getChildByName("hint");
    replaceNodeWithWidget(hintNode);

    -- @param windowNode    界面节点
    -- @param scrollNode    容器节点
    -- @param itemNode      单元格的节点
    -- @param totalNum      单元格总数
    -- @param maxRowNum     最大行数
    -- @param pageColNum    单页可以显示下的列数
    -- @param wGap          单元格间距(横向) 这里作为最小值使用
    -- @param hGap          单元格间距(纵向)
    -- @param iconWidth     单元格宽度
    -- @param iconHeight    单元格高度
    -- @param topHGap       上方留
    -- @param leftWGap      左右留白  这里作为最小值使用
    -- @param touchEvent    点击事件注册函数
    initScrollGridsVertical(self, self.scrollView, itemNode, totalCount, MAX_GRID_ROW, PAGE_COLUMN, wGap, hGap, iconWidth, iconHeight, topHGap, bottomHGap, leftWGap, nil);

    scrollToTop(self.scrollView);
end

-- 重绘
function UIWorkshopStrengthen:redraw()
    local pageNo = self.selectIndex;

    -- 获取列表
    local finalList = self:getItemListByPageNo(pageNo);
    if #finalList == 0 then
        return;
    end

    table.sort(finalList, sortItem);

    -- 显示信息
    for i = 1, #finalList do
        local grid = self.scrollView:getChildByName("item" .. i);
        if grid then
            --  初始化格子信息
            self:initItem(grid, finalList[i]);
        end
    end
end

-- 播放强化特效
function UIWorkshopStrengthen:playStrengthenEffect(id)
    self.curStrengthenId = id;
end

resize = function(self)
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT置于正中间并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end


